var path = require('path')
var CleanWebpackPlugin = require('clean-webpack-plugin').CleanWebpackPlugin
var HtmlWebpackPlugin = require('html-webpack-plugin')
var merge = require('webpack-merge')
var configDev = require('./webpack.dev.js')
var configPro = require('./webpack.pro')
var VueLoaderPlugin = require('vue-loader/lib/plugin')
var MiniCssExtractPlugin = require('mini-css-extract-plugin')
var webpack = require('webpack')
var fs = require('fs')
var { resolve } = require('./build.uitls')
const AddAssetHtmlPlugin = require('add-asset-html-webpack-plugin')

var config = {
  entry: {
    app: [resolve('./src/js/app.js')]
    // app: [resolve('./src/js/app.js')]
  },
  output: {
    path: resolve('./dist'),
    filename: '[name].[chunkhash].js'
  },
  resolve: {
    extensions: ['.js', '.jsx', '.ts', '.tsx', '.vue'],
    alias: {
      '@assets': resolve('./src/assets')
    }
  },
  optimization: {
    splitChunks: {
      name: true,
      chunks: 'all',
      minSize: 0
    },
    runtimeChunk: true
  },
  module: {
    rules: [
      {
        test: /\.ts$/,
        use: ['ts-loader']
      },
      {
        test: /\.vue$/,
        use: [
          {
            loader: 'vue-loader'
          }
        ],
        include: resolve('./src')
      },
      {
        test: /\.styl(us)?$/,
        use: [
          {
            loader: MiniCssExtractPlugin.loader,
            options: {
              esModule: false,
              reloadAll: true
            }
          },
          {
            loader: 'css-loader'
          },
          {
            loader: 'postcss-loader'
          },
          {
            loader: 'stylus-loader'
          }
        ]
      },
      {
        test: /\.(png|jpg|jepg)$/i,
        use: [
          {
            loader: 'url-loader',
            options: {
              esModule: false
            }
          }
        ]
      },
      {
        test: /.html$/,
        use: [
          {
            loader: 'html-loader'
          }
        ]
      }
    ]
  },
  plugins: [
    new CleanWebpackPlugin(),
    new HtmlWebpackPlugin({
      template: resolve('./src/index.html')
    }),
    new AddAssetHtmlPlugin([
      {
        filepath: resolve('./dll/*.js')
      }
    ]),
    new VueLoaderPlugin(),
    new MiniCssExtractPlugin({
      filename: '[name].dev.css'
    }),
    new webpack.DllReferencePlugin({
      context: __dirname,
      manifest: require('./dll/manifest.json')
    })
  ],
  devServer: {
    port: 9001,
    hot: true,
    hotOnly: false,
    overlay: true,
    proxy: {
      '/api': {
        target: 'https://www.baidu.com',
        changeOrigin: true
      }
    }
  }
}

module.exports = function(env, argv) {
  var configMerge = argv.mode === 'production' ? configPro : configDev
  config = merge(config, configMerge)
  return config
}
